package com.nondo.dean.platform.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.nondo.dean.auth.common.TokenPrincipalProvider;
import com.nondo.dean.common.tool.DateUtils;
import com.nondo.dean.common.tool.StringUtils;
import com.nondo.dean.platform.domain.Region;
import com.nondo.dean.platform.domain.RegionExample;
import com.nondo.dean.platform.domain.User;
import com.nondo.dean.platform.domain.UserExample;
import com.nondo.dean.platform.mapper.RegionMapper;
import com.nondo.dean.platform.mapper.UserExtendsMapper;
import com.nondo.dean.platform.mapper.UserMapper;
import com.nondo.dean.platform.model.UserBean;
import com.nondo.dean.platform.model.param.UserParam;
import com.nondo.dean.platform.model.result.OrderUserResult;
import com.nondo.dean.platform.model.result.UserAreaResult;

/**
 * 用户管理业务类
 *
 * @author zhaoljin
 * @date 2018年3月27日
 */
@Component
public class UserService {

    private static final Logger log = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    private UserExtendsMapper userExtendsMapper;

    @Autowired
    private TokenPrincipalProvider tokenPrincipalProvider;


    /**
     * 获取当前登录用户ID
     *
     * @return userId
     */
    public Integer getLoginUserId() {
        return tokenPrincipalProvider.getTokenPrincipal().getUserId().intValue();
    }

    /**
     * 获取当前登录用户名
     *
     * @return userId
     */
    public String getLoginUserName() {
        return tokenPrincipalProvider.getTokenPrincipal().getUsername();
    }


    /**
     * 插入用户
     *
     * @param user
     * @return
     */
    @Transactional
    public int addUser(User user) {
        return userMapper.insertSelective(user);
    }

    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @Transactional
    public int updateUser(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 按照主键ID查询用户
     *
     * @param id
     * @return
     */
    public User selectUser(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    /**
     * 用户分页查询列表
     *
     * @param offset
     * @param limit
     * @param user
     * @return
     */
    public List<User> getUserList(int offset, int limit, User user) {
        UserExample example = new UserExample();
        example.setOrderByClause("create_date DESC");
        RowBounds rowBounds = new RowBounds(offset, limit);
        UserExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, user);
        return userMapper.selectByExampleWithRowbounds(example, rowBounds);
    }

    /**
     * 用户总数统计
     *
     * @param user
     * @return
     */
    public Long count(User user) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, user);
        return userMapper.countByExample(example);
    }

    /**
     * 组装查询条件
     *
     * @param criteria
     * @param user
     */
    void setCriteria(UserExample.Criteria criteria, User user) {
        initCriteriaCondition(criteria, user);
        criteria.andDelFlagEqualTo(User.DEL_FLAG_NORMAL);
    }

    /**
     * 组装查询条件
     *
     * @param criteria
     * @param user
     */
    void setCriteriaDelFlagExist(UserExample.Criteria criteria, User user, Boolean delFlagExist) {
        initCriteriaCondition(criteria, user);
        if (!delFlagExist) {
            criteria.andDelFlagEqualTo(String.valueOf(0));
        }
    }

    private void initCriteriaCondition(UserExample.Criteria criteria, User user) {
        if (user != null) {
            if (user.getId() != null) {
                criteria.andIdEqualTo(user.getId());
            }
            if (StringUtils.isNoneBlank(user.getUserNo())) {
                criteria.andUserNoLike("%" + user.getUserNo() + "%");
            }
            if (StringUtils.isNoneBlank(user.getUserName())) {
                criteria.andUserNameLike("%" + user.getUserName() + "%");
            }
            if (StringUtils.isNoneBlank(user.getNickName())) {
                criteria.andNickNameLike("%" + user.getNickName() + "%");
            }
            if (user.getRegionId() != null) {
                criteria.andRegionIdEqualTo(user.getRegionId());
            }
            if (StringUtils.isNoneBlank(user.getRegionCode())) {
                criteria.andRegionCodeEqualTo(user.getRegionCode());
            }
            if (user.getParentId() != null) {
                criteria.andParentIdEqualTo(user.getParentId());
            }
        }
    }

    /**
     * 按照用户名称查询用户
     *
     * @param name
     * @return
     */
    public User selectUserByName(String name) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUserNameEqualTo(name);
        criteria.andDelFlagEqualTo(User.DEL_FLAG_NORMAL);
        List<User> userList = userMapper.selectByExample(example);
        return CollectionUtils.isNotEmpty(userList) ? userList.get(0) : null;
    }

    /**
     * 根据条件检索用户
     *
     * @param user 如：用户名，用户编码，用户区域
     * @return 符合条件的用户列表
     */
    public List<UserBean> getUserList(User user) {
        UserExample example = new UserExample();
        example.setOrderByClause("create_date DESC");
        UserExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, user);
        List<User> userList = userMapper.selectByExample(example);
        List<UserBean> userBeanList = new ArrayList<UserBean>();
        for (User userDb : userList) {
            UserBean userBean = UserBean.covertToBean(userDb);
            userBeanList.add(userBean);
        }
        return userBeanList;
    }

    /**
     * 根据条件检索用户
     *
     * @param user 如：用户名，用户编码，用户区域
     * @return 符合条件的用户列表
     */
    public List<UserBean> findUserList(User user) {
        UserExample example = new UserExample();
        example.setOrderByClause("create_date DESC");
        UserExample.Criteria criteria = example.createCriteria();
        setCriteriaDelFlagExist(criteria, user, true);
        List<User> userList = userMapper.selectByExample(example);
        List<UserBean> userBeanList = new ArrayList<UserBean>();
        for (User userDb : userList) {
            UserBean userBean = UserBean.covertToBean(userDb);
            userBeanList.add(userBean);
        }
        return userBeanList;
    }

    /**
     * 根据用户ID获取用户对象
     *
     * @param userId 用户ID
     * @return {@link UserBean}
     */
    public UserBean getUserById(Integer userId) {
        UserBean userBean = new UserBean();
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            return userBean;
        }
        userBean = UserBean.covertToBean(user);
        return userBean;
    }

    /**
     * 根据用户ID获取用户对象
     *
     * @param userId 用户ID
     * @return {@link UserBean}
     */
    public User findUserById(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    /**
     * 检查区域是否存在重复数据
     *
     * @return
     */
    public List<Region> checkDuplicate(Region region) {
        //检查是否存在重复的数据
        RegionExample exampleCheck = new RegionExample();
        exampleCheck.createCriteria().andCodeEqualTo(region.getCode());

        return this.regionMapper.selectByExample(exampleCheck);
    }


    /**
     * 检查经销商是否存在重复数据
     *
     * @return
     */
    public List<User> checkDuplicateUser(User user) {
        //检查是否存在重复的数据
        UserExample exampleCheck = new UserExample();
        exampleCheck.createCriteria().andUserNoEqualTo(user.getUserNo());

        return this.userMapper.selectByExample(exampleCheck);
    }

    /**
     * 新增区域入库
     *
     * @param regions
     * @return
     */
    public int insertRegion(List<Region> regions) {
        int count = 0;
        try {



            for (Region region : regions) {
                List<Region> regionList = checkDuplicate(region);
                if (regionList.size() > 0) {
                    for (Region item : regionList) {
                        RegionExample regionExample = new RegionExample();
                        regionExample.createCriteria().andCodeEqualTo(item.getCode());
                        count += regionMapper.updateByExampleSelective(region, regionExample);

                    }
                } else {
                    count += regionMapper.insertSelective(region);
                }
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }


    }

    /**
     * 查询全部区域信息
     *
     * @return newMap
     */
    public Map<String, Region> queryRegionAll() {
        Map<String, Region> newMap = new HashMap<String, Region>();
        RegionExample regionExample = new RegionExample();
        regionExample.createCriteria().andDelFlagEqualTo(String.valueOf(0));
        List<Region> regionList = regionMapper.selectByExample(regionExample);
        for (Region regions : regionList) {
            Region regionBean = new Region();
            regionBean.setId(regions.getId());
            regionBean.setCode(regions.getCode());
            regionBean.setName(regions.getName());
            newMap.put(regions.getCode(), regionBean);
        }
        return newMap;
    }



    /**
     * @return
     */
    public List<User> findAll() {
        UserExample exampleCheck = new UserExample();
        exampleCheck.setOrderByClause("user_no ASC");
        return this.userMapper.selectByExample(exampleCheck);
    }

    public Map<String, List<User>> findMapAllUser() {
        List<User> userList = findAll();
        Map<String, List<User>> userMap = new HashMap<>();
        List<User> users;
        for (User user : userList) {
            users = userMap.get(user.getUserNo());
            if (users.isEmpty()) {
                userMap.put(user.getUserNo(), new ArrayList<>());
                users = userMap.get(user.getUserNo());
            }
            users.add(user);
        }
        return userMap;
    }

    /**
     * 经销商入库
     *
     * @param users
     * @return
     */
    public int insertUser(List<User> users) {
        int count = 0;
        try {

            Map<String, List<User>> userNoMaps = findMapAllUser();

            Map<String, Region> regionMap = queryRegionAll();
            for (User user : users) {
                if (regionMap.get(user.getRegionCode()) != null) {
                    user.setRegionId(regionMap.get(user.getRegionCode()).getId());

                } else {
                    user.setRegionId(null);
                }
                if ("X".equals(user.getDelFlag())) {
                    user.setRegionId(null);
                    user.setDelFlag(User.DEL_FLAG_DELETE);
                } else {
                    user.setDelFlag(User.DEL_FLAG_NORMAL);
                }

                List<User> resUsers = userNoMaps.get(user.getUserNo());
                if (CollectionUtils.isNotEmpty(resUsers)) {
                    for (User item : resUsers) {
                        user.setId(item.getId());
                        count += userMapper.updateByPrimaryKeySelective(user);
                    }
                } else {
                    count += userMapper.insertSelective(user);
                }
                userExtendsMapper.updateUserType(user.getUserNo());
            }
            return count;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return -1;
        }


    }

    /**
     * 修改经销商对应的接单员
     *
     * @param userParam
     * @return
     */
    public int updateClerkOrdering(UserParam userParam) {
        int message;
        if (StringUtils.isNotBlank(userParam.getId())) {
            userParam.setId("''");
        } else if (StringUtils.isNotBlank(userParam.getId())) {
            userParam.setRegionId("''");
        }
        try {
            if (StringUtils.isNotBlank(userParam.getOrderTakeUser())) {
                message = userExtendsMapper.updateClerkOrdering(userParam.getRegionId(), userParam.getId(), userParam.getOrderTakeUser());
            } else {
                message = userExtendsMapper.updateClerkOrdering(userParam.getRegionId(), userParam.getId(), "");
            }
            return message;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return -1;
        }

    }

    /**
     * 查询经销商对应的接单员
     *
     * @return
     */
    public List<UserAreaResult> queryPickUpTheDealer(int offset, int limit, User user) {
        List<UserAreaResult> newList = new ArrayList<>();
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, user);
        RowBounds rowBounds = new RowBounds(offset, limit);
        List<User> users = userMapper.selectByExampleWithRowbounds(example, rowBounds);
        for (User userBean : users) {
            UserAreaResult bean = UserAreaResult.coverToBean(userBean);
            bean.setAreaName(CollectionUtils.isNotEmpty(queryById(userBean.getRegionId())) ? queryById(userBean.getRegionId()).get(0).getName() : null);
            newList.add(bean);
        }
        return newList;
    }

    /**
     * 按照区域ID查询区域信息
     *
     * @param id
     * @return
     */
    public List<Region> queryById(Integer id) {
        RegionExample regionExample = new RegionExample();
        regionExample.createCriteria().andIdEqualTo(id).andDelFlagEqualTo(String.valueOf(0));
        return regionMapper.selectByExample(regionExample);
    }


    /**
     * 查询用户基本信息
     *
     * @param request
     * @param response
     * @param id       用户ID
     * @return
     */
    public OrderUserResult getUserResult(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        OrderUserResult userResult = OrderUserResult.covertToBean(user);
        Region region = regionMapper.selectByPrimaryKey(user.getRegionId());
        userResult.setOrderCode("自动编号");
        userResult.setRegionName(region.getName());
        userResult.setOrderDate(DateUtils.getDate());
        return userResult;
    }

    /**
     * 获取用户店铺ID
     *
     * @param userId
     * @return
     */
    public Integer queryStoreId(Integer userId) {
        UserExample example = new UserExample();
        example.createCriteria().andIdEqualTo(userId).andDelFlagEqualTo(User.DEL_FLAG_NORMAL);
        User list = userMapper.selectByExample(example).get(0);
        return list.getStoreId();
    }

    /**
     * 根据手机号获取用户基本信息
     *
     * @param mobile
     * @return
     */
    public User selectUserByMobile(String mobile) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andMobileEqualTo(mobile);
        criteria.andDelFlagEqualTo(User.DEL_FLAG_NORMAL);
        List<User> userList = userMapper.selectByExample(example);
        return CollectionUtils.isNotEmpty(userList) ? userList.get(0) : null;
    }
}
